//配置文件路径
const configPath = "/sdcard/catHelp.txt"
var configData = {}
//是否需要效验卡密
var isNeedVerify = true
//读配置文件数据
function readConfig () {
    let params = {}
    try {
        let p = files.read(configPath)
        params = JSON.parse(p)
        configData = params
    } catch (e) {
        console.log("读取配置文件数据异常:" + e)
    }
    return params
}

//写配置文件数据
function writeConfig (params) {
    try {
        configData = params
        files.write(configPath, JSON.stringify(params))
        return true
    } catch (e) {
        console.log("写入配置文件数据异常:" + e)
        return false
    }
}

//更新卡密信息
function updateCardInfo (params) {
    threads.start(function () {
        try {
            let msg
            if (isNeedVerify) {
                //卡密
                let keygen = params.keygen
                if (!keygen) {
                    toastLog("请输入卡密")
                    return
                }
                var url = "http://43.138.184.61:7151/app-api/verify/card/bind";
                // var url = "http://192.168.31.212:48080/app-api/verify/card/bind";
                let id;
                if (device.sdkInt < 29) {
                    id = device.getIMEI();
                } else {
                    id = device.getAndroidId();
                }
                let deviceId = null;
                try {
                    let p = files.read(configPath)
                    p = JSON.parse(p)
                    if (p.deviceId === undefined || p.deviceId === null || p.deviceId === "") {
                        deviceId = id;
                    } else {
                        deviceId = p.deviceId;
                    }
                } catch (e) {
                    deviceId = id;
                }
                let r = http.postJson(url, {
                    "cardNumber": keygen,
                    "cardDeviceNumber": deviceId
                });
                let d = JSON.parse(r.body.string())
               
                if (d.code === 0) {
                    msg = "激活成功"
                } else {
                    msg = d.msg
                }
                params.jh_result = msg
                params.deviceId = deviceId
            } else {
                msg = "保存成功"
            }
            writeConfig(params)
            toastLog(msg)
        } catch (e) {
            console.log(e)
            toastLog("卡密服务异常,请检查网络")
        }
    });
}


//效验卡密信息
function checkCar () {
    let keygen = ui.keygen.text()
    if (!keygen) {
        toastLog("请输入卡密")
        return false
    }
    let jh = configData.jh_result
    console.log(jh)
    if (jh === "激活成功") {
        return true
    } else {
        toastLog(jh)
        return false;
    }
}

exports.checkCar = checkCar;
exports.updateCardInfo = updateCardInfo;
exports.readConfig = readConfig;
exports.writeConfig = writeConfig;